package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.Vector;

/**
 * <p>
 * Test16批量重偏向
 * </p>
 *
 * @author flyduck
 * @since 2023/9/7
 */
@Slf4j(topic = "c.Test18_批量重偏向")
public class Test18_批量重偏向 {
    public static void main(String[] args) throws InterruptedException {
        Thread.sleep(4000);
        Vector<Dog> list = new Vector<>();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                Dog d = new Dog();
                list.add(d);
                synchronized (d) {
                    //可偏向锁（偏向t1线程）：00000000 00000000 00000000 00000000 00011110 10111111 11010000 00000101
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                }
            }
            synchronized (list) {
                list.notify();
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            synchronized (list) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug("===============> ");
            for (int i = 0; i < 30; i++) {
                Dog d = list.get(i);
                //可偏向锁（偏向t1线程）：      00000000 00000000 00000000 00000000 00011110 10111111 11010000 00000101
                //20次，可偏向锁（偏向t1线程）：00000000 00000000 00000000 00000000 00011110 10111111 11010000 00000101
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                synchronized (d) {
                    //轻量级锁：                   00000000 00000000 00000000 00000000 00100000 01011100 11110101 00010000
                    //20次，可偏向锁（偏向t2线程）：00000000 00000000 00000000 00000000 00011110 10111111 10001001 00000101
                    log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
                }
                //不可偏向：                   00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001
                //20次，可偏向锁（偏向t2线程）：00000000 00000000 00000000 00000000 00011110 10111111 10001001 00000101
                log.debug(i + "\t" + ClassLayout.parseInstance(d).toPrintableSimple());
            }
        }, "t2");
        t2.start();
    }
}
